<template>
  <div class="post-preview" v-if="visible" @click.self="handleClose">
    <div class="preview-container">
      <!-- 左侧图片区域 -->
      <div class="preview-images">
        <el-carousel :interval="4000" arrow="always" indicator-position="none">
          <el-carousel-item v-for="image in post.images" :key="image">
            <img :src="image" :alt="post.title" class="preview-image" />
          </el-carousel-item>
        </el-carousel>
      </div>

      <!-- 右侧内容区域 -->
      <div class="preview-content">
        <!-- 用户信息区 -->
        <div class="user-info">
          <div class="user-basic">
            <el-avatar :src="post.author.avatar" :size="36" />
            <span class="nickname">{{ post.author.nickname }}</span>
          </div>
          <el-button
            :type="post.author.isFollowed ? 'default' : 'primary'"
            size="small"
            @click="handleFollow"
          >
            {{ post.author.isFollowed ? '已关注' : '关注' }}
          </el-button>
        </div>

        <!-- 帖子内容区 -->
        <div class="post-content">
          <h2 class="post-title">{{ post.title }}</h2>
          <p class="post-text">{{ post.content }}</p>
          <div class="post-location" v-if="post.location">
            <el-icon><Location /></el-icon>
            <span>{{ post.location }}</span>
          </div>
        </div>

        <!-- 评论区 -->
        <div class="comments-section">
          <div class="comments-list" ref="commentsList">
            <div v-for="comment in comments" :key="comment.id" class="comment-item">
              <el-avatar :src="comment.avatar" :size="28" />
              <div class="comment-content">
                <div class="comment-user">
                  <span class="comment-nickname">{{ comment.nickname }}</span>
                  <span v-if="comment.replyTo">
                    回复
                    <span class="reply-nickname">@{{ comment.replyTo }}</span>
                  </span>
                </div>
                <p class="comment-text">{{ comment.content }}</p>
                <div class="comment-actions">
                  <span class="comment-time">{{ formatTime(comment.createdAt) }}</span>
                  <span class="comment-like" @click="handleCommentLike(comment)">
                    <el-icon><Star /></el-icon>
                    {{ comment.likeCount }}
                  </span>
                  <span class="comment-reply" @click="handleReply(comment)">回复</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部操作区 -->
        <div class="preview-footer">
          <div class="comment-input">
            <el-input
              v-model="commentText"
              :placeholder="replyTo ? `回复 @${replyTo}` : '说点什么...'"
              @keyup.enter="handleComment"
            >
              <template #append>
                <el-button @click="handleComment">发送</el-button>
              </template>
            </el-input>
          </div>
          <div class="action-buttons">
            <div class="action-button" @click="handleLike">
              <el-icon :class="{ 'is-active': post.isLiked }"><Star /></el-icon>
              <span>{{ post.likeCount }}</span>
            </div>
            <div class="action-button" @click="handleCollect">
              <el-icon :class="{ 'is-active': post.isCollected }"><Collection /></el-icon>
              <span>{{ post.collectCount }}</span>
            </div>
            <div class="action-button" @click="handleShare">
              <el-icon><Share /></el-icon>
              <span>分享</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 关闭按钮 -->
      <div class="close-button" @click="handleClose">
        <el-icon><Close /></el-icon>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { usePostStore } from '@/store/post'
import { useUserStore } from '@/store/user'
import { Star, Collection, Share, Location, Close } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  postId: {
    type: [String, Number],
    required: true
  }
})

const emit = defineEmits(['update:visible', 'refresh'])

const postStore = usePostStore()
const userStore = useUserStore()
const post = ref({})
const comments = ref([])
const commentText = ref('')
const replyTo = ref('')
const loading = ref(false)

// 获取帖子详情
const fetchPostDetail = async () => {
  try {
    loading.value = true
    const response = await postStore.fetchPostDetail(props.postId)
    post.value = response.data
    await fetchComments()
  } catch (error) {
    ElMessage.error('获取帖子详情失败')
  } finally {
    loading.value = false
  }
}

// 获取评论列表
const fetchComments = async () => {
  try {
    const response = await postStore.fetchPostComments(props.postId, {
      page: 1,
      limit: 20
    })
    comments.value = response.items
  } catch (error) {
    ElMessage.error('获取评论失败')
  }
}

// 关注/取消关注
const handleFollow = async () => {
  try {
    if (post.value.author.isFollowed) {
      await userStore.unfollowUser(post.value.author.id)
    } else {
      await userStore.followUser(post.value.author.id)
    }
    post.value.author.isFollowed = !post.value.author.isFollowed
    ElMessage.success(post.value.author.isFollowed ? '关注成功' : '取消关注成功')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 点赞/取消点赞
const handleLike = async () => {
  try {
    await postStore.togglePostLike(props.postId, post.value.isLiked)
    if (post.value.isLiked) {
      post.value.likeCount--
    } else {
      post.value.likeCount++
    }
    post.value.isLiked = !post.value.isLiked
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 收藏/取消收藏
const handleCollect = async () => {
  try {
    await postStore.togglePostCollect(props.postId, post.value.isCollected)
    if (post.value.isCollected) {
      post.value.collectCount--
    } else {
      post.value.collectCount++
    }
    post.value.isCollected = !post.value.isCollected
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 分享
const handleShare = () => {
  // 实现分享逻辑
  ElMessage.success('分享功能开发中')
}

// 发表评论
const handleComment = async () => {
  if (!commentText.value.trim()) {
    return ElMessage.warning('请输入评论内容')
  }

  try {
    const response = await postStore.submitComment(props.postId, {
      content: commentText.value,
      replyTo: replyTo.value ? replyTo.value.id : null
    })
    
    comments.value.unshift(response)
    commentText.value = ''
    replyTo.value = null
    post.value.commentCount++
    ElMessage.success('评论成功')
  } catch (error) {
    ElMessage.error('评论失败')
  }
}

// 回复评论
const handleReply = (comment) => {
  replyTo.value = {
    id: comment.userId,
    nickname: comment.nickname
  }
  // 聚焦输入框
  document.querySelector('.comment-input input').focus()
}

// 评论点赞
const handleCommentLike = async (comment) => {
  try {
    await postStore.toggleCommentLike(comment.id, comment.isLiked)
    if (comment.isLiked) {
      comment.likeCount--
    } else {
      comment.likeCount++
    }
    comment.isLiked = !comment.isLiked
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false)
  // 重置状态
  commentText.value = ''
  replyTo.value = null
}

// 格式化时间
const formatTime = (time) => {
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  
  // 小于1分钟
  if (diff < 60000) {
    return '刚刚'
  }
  // 小于1小时
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  }
  // 小于24小时
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  }
  // 小于30天
  if (diff < 2592000000) {
    return `${Math.floor(diff / 86400000)}天前`
  }
  // 显示具体日期
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 监听 visible 变化
watch(() => props.visible, (newVal) => {
  if (newVal && props.postId) {
    fetchPostDetail()
  }
})

// 监听 postId 变化
watch(() => props.postId, (newVal) => {
  if (props.visible && newVal) {
    fetchPostDetail()
  }
})
</script>

<style lang="scss" scoped>
.post-preview {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;

  .preview-container {
    display: flex;
    width: 960px;
    height: 80vh;
    background: #fff;
    border-radius: 8px;
    position: relative;
    overflow: hidden;
  }

  .preview-images {
    width: 60%;
    height: 100%;
    background: #000;

    .preview-image {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
  }

  .preview-content {
    width: 40%;
    height: 100%;
    display: flex;
    flex-direction: column;
    position: relative;
    padding: 24px;

    .user-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .user-basic {
        display: flex;
        align-items: center;
        gap: 12px;

        .nickname {
          font-weight: 600;
          font-size: 16px;
        }
      }
    }

    .post-content {
      flex: 1;
      overflow-y: auto;
      padding-right: 12px;
      margin-bottom: 20px;

      .post-title {
        font-size: 18px;
        font-weight: 600;
        margin-bottom: 12px;
      }

      .post-text {
        font-size: 14px;
        line-height: 1.6;
        color: #333;
        white-space: pre-wrap;
      }

      .post-location {
        display: flex;
        align-items: center;
        gap: 4px;
        color: #999;
        font-size: 12px;
        margin-top: 12px;
      }
    }

    .comments-section {
      flex: 1;
      overflow-y: auto;
      border-top: 1px solid #eee;
      padding-top: 20px;

      .comment-item {
        display: flex;
        gap: 12px;
        margin-bottom: 16px;

        .comment-content {
          flex: 1;

          .comment-user {
            margin-bottom: 4px;

            .comment-nickname {
              font-weight: 500;
              margin-right: 4px;
            }

            .reply-nickname {
              color: #666;
            }
          }

          .comment-text {
            font-size: 14px;
            margin-bottom: 4px;
          }

          .comment-actions {
            display: flex;
            gap: 16px;
            color: #999;
            font-size: 12px;

            span {
              cursor: pointer;

              &:hover {
                color: #333;
              }
            }
          }
        }
      }
    }

    .preview-footer {
      border-top: 1px solid #eee;
      padding-top: 16px;

      .comment-input {
        margin-bottom: 16px;
      }

      .action-buttons {
        display: flex;
        justify-content: flex-end;
        gap: 24px;

        .action-button {
          display: flex;
          align-items: center;
          gap: 4px;
          cursor: pointer;
          color: #666;

          &:hover {
            color: #333;
          }

          .is-active {
            color: #ff2442;
          }
        }
      }
    }
  }

  .close-button {
    position: absolute;
    top: 16px;
    right: 16px;
    width: 32px;
    height: 32px;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      background: rgba(0, 0, 0, 0.7);
    }
  }
}

// 自定义滚动条样式
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
}

::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #555;
}
</style>
